package com.pigs.springbootpigsmongodbcomment.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.pigs.springbootpigsmongodbcomment.entity.CommentEntity;
import com.pigs.springbootpigsmongodbcomment.service.CommentService;
import com.pigs.springbootpigsmongodbcomment.utils.TimeUtitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author PIGS
 * @version 1.0
 * @date 2020/4/23 19:46
 * @effect :
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加评论
     *
     * @param comment
     * @return
     */
    @Override
    public CommentEntity saveComment(CommentEntity comment) {
        comment.setCreateDateTime(TimeUtitl.dateTime());
        comment.setLikeNum(0);
        comment.setReplyNum(0);
        comment.setState(1);
        comment.setParentId(0);
        comment.setArticleId(1);
        comment.setUserId(System.currentTimeMillis());
        String random = "";
        String[] doc = {"猪八戒", "貂蝉", "奥特曼", "秦始皇", "诸葛亮"};
        int index = (int) (Math.random() * doc.length);
        random = doc[index];
        comment.setNickName(random);
        CommentEntity comment1 = mongoTemplate.save(comment, "comment");
        return comment1;
    }

    /**
     * 查询评论
     *
     * @return
     */
    @Override
    public List<CommentEntity> queryComments() {
        List<CommentEntity> comment = mongoTemplate.findAll(CommentEntity.class, "comment");
        return comment;
    }

    /**
     * 删除评论实现类
     *
     * @param userId
     * @return
     */
    @Override
    public DeleteResult delComment(Long userId) {

        Query query = new Query(Criteria.where("userId").is(userId));
        DeleteResult remove = mongoTemplate.remove(query, CommentEntity.class, "comment");
        return remove;
    }

    /**
     * 实现点赞功能
     *
     * @param userId
     * @return
     */
    @Override
    public CommentEntity clickLine(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        Update update = new Update();
        update.inc("likeNum", 1);
        CommentEntity comment = mongoTemplate.findAndModify(query, update, CommentEntity.class, "comment");
        return comment;
    }
}
